//
//  XhwStrangerVC.m
//  SelfDriving
//
//  Created by 熊宏伟 on 2018/1/22.
//  Copyright © 2018年 apple. All rights reserved.
//

#import "XhwStrangerVC.h"
#import "MsgCell.h"
#import "ChatViewController.h"


@interface XhwStrangerVC ()<UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *table;


@property (nonatomic,strong) NSMutableArray * positionFor4ModeImage;
@property (nonatomic,strong) NSMutableArray * positionFor9ModeImage;
@end

@implementation XhwStrangerVC
{
    NSMutableArray *contentArr;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
//    self.navigationItem.hidesBackButton = YES;
    self.title = @"陌生人消息";
//    [self setNavItem];
    [self initUI];
}

- (void)setNavItem {
    UIImage* backImage = [UIImage imageNamed:@"back_p.png"];
    CGRect backframe = CGRectMake(0,0,54,30);
    UIButton* backButton= [[UIButton alloc] initWithFrame:backframe];
    [backButton setBackgroundImage:backImage forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];

    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
}

- (void)backAction:(UIBarButtonItem *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    NSLog(@"xhw->陌生人消息->viewWillAppear");
    [self initData];
}

- (void)initUI {
    _table.frame = self.view.frame;
    _table.delegate = self;
    _table.dataSource = self;
    _table.tableFooterView=[[UIView alloc]init];//关键语句
    
}

- (void)initData {
    contentArr = [[NSMutableArray alloc] init]; //注意:必须初始化
    
    NSMutableArray *xhwcontentArr = (NSMutableArray *)[TCSession getSessionListTimeLine];
    NSLog(@"strangerVC->xhwcontentArr.count:%lu",(unsigned long)xhwcontentArr.count);
    for (int i = 0; i<xhwcontentArr.count; i++) {
        TCSession *session = [xhwcontentArr objectAtIndex:i];
        
        NSMutableArray *resultArray = (NSMutableArray *)[[ThinkChat instance] getMessageListTimeLineWithID:session.ID typeChat:session.typeChat sinceRowID:0 maxRowID:0 count:0 page:0];
        NSLog(@"resultArray.count->%lu",(unsigned long)resultArray.count);
        if (resultArray.count != 0) {
            TCMessage * xhwMessage = resultArray[resultArray.count - 1];
            NSLog(@"xhwMessage->%@",xhwMessage);
            NSLog(@"xhwMessage.to->%@",xhwMessage.to);
            NSLog(@"xhwMessage.to.isfriend->%@",[xhwMessage.to getExtendValueForKey:@"isfriend"]);
            session.message = xhwMessage;
            if ([[xhwMessage.to getExtendValueForKey:@"isfriend"] isEqualToString:@"0"]) {
                NSLog(@"走进去了");
                [contentArr addObject:session];
                NSLog(@"strangerVC->contentArr1.count:%lu",(unsigned long)contentArr.count);
            }
        }
    }
    NSLog(@"strangerVC->contentArr2.count:%lu",(unsigned long)contentArr.count);
    [_table reloadData];
}

- (UIImage *)makeGroupAvatar: (NSMutableArray *)imageArray {
    //数组为空，退出函数
    if ([imageArray count] == 0){
        return nil;
    }
    
    UIView *groupAvatarView = [[UIView alloc]initWithFrame:CGRectMake(0,0,193,193)];
    groupAvatarView.backgroundColor = UIColorFromRGB(0xEFEFF4);
    
    for (int i = 0; i < [imageArray count]; i++){
        UIImageView *tempImageView;
        if ([imageArray count] < 5){
            tempImageView = [[UIImageView alloc]initWithFrame:[[_positionFor4ModeImage objectAtIndex:i]CGRectValue]];
        }
        else{
            tempImageView = [[UIImageView alloc]initWithFrame:[[_positionFor9ModeImage objectAtIndex:i]CGRectValue]];
        }
        UIImage *imgss = [imageArray objectAtIndex:i];
        imgss = [UIImage createRoundedRectImage:imgss size:imgss.size radius:imgss.size.width/2];
        [tempImageView setImage:[UIImage borderImg:imgss]];
        [groupAvatarView addSubview:tempImageView];
    }
    
    //把UIView设置为image并修改图片大小55*55
    UIImage *reImage = [self scaleToSize:[self convertViewToImage:groupAvatarView]size:CGSizeMake(80, 80)];
    
    return reImage;
}

- (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size{
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(size);
    // 绘制改变大小的图片
    [img drawInRect:CGRectMake(0, 0, size.width, size.height)];
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    
    
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    // 返回新的改变大小后的图片
    return scaledImage;
}

-(UIImage*)convertViewToImage:(UIView*)v{
    
    CGSize s = v.bounds.size;
    
    // 下面方法，第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果，需要传NO，否则传YES。第三个参数就是屏幕密度了，关键就是第三个参数。
    
    UIGraphicsBeginImageContextWithOptions(s, YES, [UIScreen mainScreen].scale);
    
    [v.layer renderInContext:UIGraphicsGetCurrentContext()];
    
    UIImage*image = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return image;
    
}


#pragma mark -UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return contentArr.count;
}

#pragma mark -UItableViewDataSource

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    [[AppDelegate shareDelegate]showMsgCount];
    TCSession *msg = [contentArr objectAtIndex:indexPath.row];
    NSLog(@"%@",msg.content);
    NSLog(@"%@",msg.name);
    MsgCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MsgCell"];
    
    if (msg.typeChat == 300) {
        NSMutableArray *heads = [[NSMutableArray alloc]init];
        NSArray *array = [msg.head componentsSeparatedByString:@","];
        for (NSString *img in array) {
            if (img.length == 0) {
                continue;
            }
            UIImageView *ims = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
            ims.layer.cornerRadius = ims.frame.size.width/2;
            ims.clipsToBounds = YES;
            [ValidateHelper setimgeSize:img img:ims];
            [heads addObject:ims.image];
        }
        cell.img.backgroundColor = [UIColor clearColor];
        if (heads.count == 0) {
            [cell.img sd_setImageWithURL:[NSURL URLWithString:msg.head]
                        placeholderImage:[UIImage imageNamed:@"notimgs"]];
            
        }else{
            cell.img.image = [self makeGroupAvatar:heads];
        }
    }else{
        cell.img.layer.cornerRadius = cell.img.frame.size.width/2;
        cell.img.clipsToBounds = YES;
        [cell.img sd_setImageWithURL:[NSURL URLWithString:msg.head]
                    placeholderImage:[UIImage imageNamed:@"notimgs"]];
    }
    if([msg.content rangeOfString:@"红包"].location !=NSNotFound){
        cell.textContent.text = @"[红包]";
    }else if([msg.content rangeOfString:@"LabVideo"].location !=NSNotFound){
        cell.textContent.text = @"[视频]";
    }
    else if([msg.content rangeOfString:@"转赠"].location !=NSNotFound){
        cell.textContent.text = @"[转赠]";
    }
    else if([msg.content rangeOfString:@"共享"].location !=NSNotFound){
        cell.textContent.text = @"[位置共享]";
    }
    else if([msg.content rangeOfString:@"LabLocation"].location !=NSNotFound){
        cell.textContent.text = @"[位置]";
    }
    else if([msg.content rangeOfString:@"LabAudio"].location !=NSNotFound){
        cell.textContent.text = @"[声音]";
    }
    else if([msg.content rangeOfString:@"LabImage"].location !=NSNotFound){
        cell.textContent.text = @"[图片]";
    }else{
        [ValidateHelper ReplaceExpression:msg.content label:cell.textContent size:14 isr:NO];
    }
    

    cell.name.text = msg.name;
    
    NSString *time = [ValidateHelper timeStringWith:msg.time multiLine:NO];
    NSString *distance = [msg getExtendValueForKey:@"distance"];
    if (distance) {
        
    }
    else {
        distance = 0;
    }
    if (msg.unreadCount!=0) {
        [cell.unreadCount setTitle:[NSString stringWithFormat:@"%d",msg.unreadCount] forState:UIControlStateNormal];
        cell.unreadCount.hidden = NO;
    }else{
        cell.unreadCount.hidden = YES;
    }
    //    cell.time.text = time;
    //xhw2018-1-19改bug15265
    cell.time.text = [NSString stringWithFormat:@"%@|%@",[ValidateHelper DistanceFormat:distance],time];
    return  cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    TCSession *msg = [contentArr objectAtIndex:indexPath.row];
    MsgCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"MS"
                                                                 bundle:[NSBundle mainBundle]];
    ChatViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"ChatVC"];
    searchResultDetailController.image = cell.img.image;
    searchResultDetailController.tcs = msg;
    [self.navigationController pushViewController:searchResultDetailController animated:YES];

}

#pragma mark 设置可以进行编辑

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath

{
    return YES;
}
#pragma mark 设置编辑的样式

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath

{
    
    return UITableViewCellEditingStyleDelete;
    
}
#pragma mark 设置可以移动

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath

{
    
    return YES;
    
}

- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath

{
    
    // 添加一个删除按钮
    
    UITableViewRowAction *deleteRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        
        NSLog(@"点击了删除");
        
        TCSession * item = [contentArr objectAtIndex:indexPath.row];
      
        [[AppDelegate shareDelegate] clearSessionID:item.ID typeChat:item.typeChat];
        [self initData];
        [[AppDelegate shareDelegate]showMsgCount]; //xhw2018-1-26加
        // 1. 更新数据
        
        //        [_allDataArray removeObjectAtIndex:indexPath.row];
        
        // 2. 更新UI
        
        //        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        
    }];
    
    
    
    // 删除一个置顶按钮
    
    UITableViewRowAction *topRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"置顶" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
       
    }];
    
    topRowAction.backgroundColor = UIColorFromRGB(0x996633);
    
    
    
    // 添加一个更多按钮
    
    UITableViewRowAction *moreRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"忽略未读" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        NSLog(@"点击了更多");
        
        
        
        TCSession * item = [contentArr objectAtIndex:indexPath.row];
        

            
        [[ThinkChat instance]hasReadSessionID:item.ID typeChat:item.typeChat];
            
        
        [self initData];
        [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationMiddle];
        
    }];
    
    moreRowAction.backgroundColor = [UIColor lightGrayColor];
    
    
    // 将设置好的按钮放到数组中返回
    
    // return @[deleteRowAction, topRowAction, moreRowAction];
    
    return @[deleteRowAction,moreRowAction,topRowAction];
    
}



@end
